#include <iostream>
#include <cstring>
#include <unistd.h>

#include "common3.hpp"

using namespace std;

int main()
{
    // 客户端：写入
    shm c(CLIENT);

    char *start = (char *)c.getStart();
    int wfd = c.getWFD();
    int rfd = c.getRFD();

    const char *str = "yes";

    srand((size_t)time(NULL));

    char buff[64];
    while (true)
    {
    	// 等待服务端发出操作命令
        int n = read(rfd, buff, sizeof(buff) - 1);
        buff[n] = 0;

        if (n > 0)
        {
            if (strcasecmp(str, buff) == 0)
            {
                printf("client write# ");
                fflush(stdout);

                fgets(buff, sizeof buff, stdin);
                int i = 0;
                while(buff[i] != '\n')
                {
                    start[i] = buff[i];
                    i++;
                }
                buff[i] = start[i] = 0;


                // 写入完成，通知服务端读取
                write(wfd, str, strlen(str));

                if (strcasecmp("exit", buff) == 0)
                    break;
            }
        }
        else if (n == 0)
        {
            cerr << "客户端未从管道中读取到数据" << endl;
        }
        else
        {
            cerr << "读取异常" << endl;
            break;
        }
    }

    return 0;
}
